﻿using System.IO;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using System.Runtime.Serialization;
using System;

namespace KstopaCommon
{
    /// <summary>
    /// Dictionary(支持XML序列化)
    /// </summary>
    /// <typeparam name="TKey">键类型</typeparam>
    /// <typeparam name="TValue">值类型</typeparam>
    [XmlRoot("XmlDictionary")]
    [Serializable]
    public class XmlDictionary<TKey, TValue> : Dictionary<TKey, TValue>, IXmlSerializable
    {
        public XmlDictionary() { }
        public XmlDictionary(IDictionary<TKey, TValue> dictionary) : base(dictionary) { }
        public XmlDictionary(IEqualityComparer<TKey> comparer) : base(comparer) { }
        public XmlDictionary(int capacity) : base(capacity) { }
        public XmlDictionary(int capacity, IEqualityComparer<TKey> comparer) : base(capacity, comparer) { }
        protected XmlDictionary(SerializationInfo info, StreamingContext context) : base(info, context) { }

        public void Serialize(string fileName)
        {
            using (FileStream fs = new FileStream(fileName, FileMode.Create))
            {
                XmlSerializer formatter = new XmlSerializer(GetType());
                formatter.Serialize(fs, this);
            }
        }

        public XmlDictionary<TKey, TValue> Deserialize(string fileName)
        {
            if (File.Exists(fileName))
            {
                using (FileStream fs = new FileStream(fileName, FileMode.Open))
                {
                    XmlSerializer formatter = new XmlSerializer(GetType());
                    return formatter.Deserialize(fs) as XmlDictionary<TKey, TValue>;
                }
            }
            return null;
        }

        #region IXmlSerializable
        public XmlSchema GetSchema() => null;
        /// <summary>
        /// 从对象的XML表示形式生成该对象(反序列化)
        /// </summary>
        /// <param name="reader"></param>
        public void ReadXml(XmlReader reader)
        {
            if (reader.IsEmptyElement)
            {
                return;
            }
            var ks = new XmlSerializer(typeof(TKey));
            var vs = new XmlSerializer(typeof(TValue));
            reader.Read();
            while (reader.NodeType != XmlNodeType.EndElement)
            {
                reader.ReadStartElement("Item");
                reader.ReadStartElement("Key");
                var key = (TKey)ks.Deserialize(reader);
                reader.ReadEndElement();
                reader.ReadStartElement("Value");
                var value = (TValue)vs.Deserialize(reader);
                reader.ReadEndElement();
                Add(key, value);
                reader.ReadEndElement();
                reader.MoveToContent();
            }
            reader.ReadEndElement();
        }
        /// <summary>
        /// 将对象转换为其XML表示形式(序列化)
        /// </summary>
        /// <param name="writer"></param>
        public void WriteXml(XmlWriter writer)
        {
            var ks = new XmlSerializer(typeof(TKey));
            var vs = new XmlSerializer(typeof(TValue));
            foreach (var key in Keys)
            {
                writer.WriteStartElement("Item");
                writer.WriteStartElement("Key");
                ks.Serialize(writer, key);
                writer.WriteEndElement();
                writer.WriteStartElement("Value");
                vs.Serialize(writer, this[key]);
                writer.WriteEndElement();
                writer.WriteEndElement();
            }
        }
        #endregion
    }
}
